

<?php
	/*
	Generate JS array items like this:
	var items=[
		  {description:"Blouse Red",code:"220B",imageUrl:"170b.JPG",price:100.0},
		  {description:"Dress Blue",code:"100D",imageUrl:"170b.JPG",price:200.0},
		  {description:"Blouse Red",code:"220B",imageUrl:"170b.JPG",price:100.0},
		  {description:"Dress White",code:"100D",imageUrl:"170b.JPG",price:200.0}
		]
	*/

	$items = listItems();

	$filename = "./items.js";
	$file = fopen( $filename, "w" );
	if( $file == false )
	{
	   echo ( "Error in opening new file" );
	   exit();
	}

	fwrite( $file, "var items=[\n" );
	$count = count($items);
	for($x=0;$x<$count;$x++) {
	   $baseName =	str_ireplace(array(".jpg",".png",".gif"), "", $items[$x]);
	   $tokens = explode('-', $baseName);
	   $description = $tokens[0];
	   $code = $tokens[1];
	   $imageUrl = rawurlencode($items[$x]);
	   $price = $tokens[2];
	   fwrite( $file, '{description:"'. $description .'",code:"'. $code .'",imageUrl:"'. $imageUrl .'",price:'. $price .'}'. ( ($count - 1 == $x) ? '' : ',' ) ."\n" );
	}
	fwrite( $file, "]" );

	fclose( $file );
	
	if( file_exists( $filename ) )
	{
	   readAndEchoFile($filename);
	}
	else
	{
	   echo ("Failed to create $filename" );
	}

	function readAndEchofile($filename) {
		$filesize = filesize( $filename );
		$msg = "File  created with name $filename ";
		$msg .= "containing $filesize bytes";
		echo ($msg );
		$file = fopen( $filename, "r" );
		if( $file == false )
		{
		  echo ( "Error in opening file" );
		  exit();
		}
		$filesize = filesize( $filename );
		$filetext = fread( $file, $filesize );

		fclose( $file );

		echo ( "File size : $filesize bytes" );
		echo ( "<pre>$filetext</pre>" );
	}
	

	function listItems() {
		$items = array();
		$i = 0;
		if ($handle = opendir('./index_files/itemimages')) {
		    while (false !== ($entry = readdir($handle))) {
			if ($entry != "." && $entry != "..") {
			    $items[$i++] = $entry;
			}
		    }
		    closedir($handle);
		}
		return $items;
	}
?>
